﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IngredSubTool
{
    public class Substitution : INotifyPropertyChanged
    {
        private String _original;
        public String Original
        {
            get { return _original; }
            set { _original = value; NotifyPropertyChanged("Original"); }
        }
        private String _replacement;
        public String Replacement
        {
            get { return _replacement; }
            set { _replacement = value; NotifyPropertyChanged("Replacement"); }
        }
        private String _description;
        public String Description
        {
            get { return _description; }
            set { _description = value; NotifyPropertyChanged("Description"); }
        }
        private String _categories;
        public String Categories
        {
            get { return _categories; }
            set { _categories = value; NotifyPropertyChanged("Categories"); }
        }
        private double _averagerating = 0;
        public double AverageRating
        {
            get { return _averagerating; }
            set { _averagerating = value; NotifyPropertyChanged("AverageRating"); }
        }
        public ObservableCollection<Comment> Comments { get; set; }
        public Tuple<double, double, string, string> Ratios { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public Substitution(String newOrig, String newRepl, String desc, String cats, String ratios)
        {
            Original = newOrig;
            Replacement = newRepl;
            Description = desc;
            Categories = cats;
            Comments = new ObservableCollection<Comment>();
            String[] splitRatios = ratios.Split(':');
            Ratios = new Tuple<double, double, string, string>(double.Parse(splitRatios[0]), double.Parse(splitRatios[1]), splitRatios[2], splitRatios[3]);
        }

        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void UpdateAverage()
        {
            if (Comments.Count < 1)
            {
                AverageRating = 0;
                return;
            }

            double averageTotal = 0;
            double averageCount = 0;
            foreach (Comment com in Comments)
            {
                if (com.Rating > 0)
                {
                    averageTotal += com.Rating;
                    averageCount++;
                }
            }
            AverageRating = (averageTotal / Comments.Count);
        }
    }
}
